package com.lanchewuyou.user.driver.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.adapter.PhotoAdapter;
import com.lanchewuyou.user.driver.lipeiui.CaseInfoActivity;
import com.lanchewuyou.user.driver.lipeiui.CaseReturnActivity;
import com.lanchewuyou.user.driver.lipeiui.CompanyActivity;
import com.lanchewuyou.user.driver.lipeiui.PickCarActivity;
import com.lanchewuyou.user.driver.lipeiui.ReturnCarActivity;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * 从相册选取多图上传.拿到照片路径之后进行裁剪压缩并一一对应进行上传
 */

public class CarPhotoActivity extends AppCompatActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private ImageView choosePhoImg;
    private TextView inputFolderName;
    private RecyclerView carPhoRecycler;
    private Button uploadCarPho, carPhoNextBtn;
    PhotoAdapter photoAdapter;
    ArrayList<String> selectedPhotos = new ArrayList<>();
    private String PHOTO_FOLDER = new File(Environment.getExternalStorageDirectory(), "").getPath() + "/lanchewuyou/";

    private String PHOTO_FOLDER_CARPHOTO = PHOTO_FOLDER + "carphoto/";
    public final static int REQUEST_CODE = 1;
    public static CarPhotoActivity instance;
    private String FROMWHERE;
    private String orderId, driverId;
    private String PHOTO_NAME;
    private int type;
    private long time;

    private ProgressDialog progressDialog;

    private Toast toast1 = null;

    private void showTextToast(String msg) {
        if (toast1 == null) {
            toast1 = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast1.setText(msg);
        }
        toast1.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_photo);
        Intent intent = getIntent();
        FROMWHERE = intent.getStringExtra("from");
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        driverId = sharedPreferences.getString("driverid", "");
        if (FROMWHERE.equals("personpho")) {
            orderId = PickCarActivity.orderId;
            PHOTO_NAME = orderId + driverId + 7;
            type = 7;
        } else if (FROMWHERE.equals("returncar")) {
            orderId = ReturnCarActivity.ORDERID;
            PHOTO_NAME = orderId + driverId + 8;
            type = 8;
        } else if (FROMWHERE.equals("caseinfo")) {
            orderId = CaseInfoActivity.orderId;
            PHOTO_NAME = orderId + driverId + 7;
            type = 7;
        } else if (FROMWHERE.equals("casereturn")) {
            orderId = CaseReturnActivity.orderId;
            PHOTO_NAME = orderId + driverId + 8;
            type = 8;
        }
        initViews();
        instance = this;
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(PHOTO_FOLDER);
            if (!file.exists()) {
                file.mkdir();
            } else {
                Log.d("carphoto", PHOTO_FOLDER);
            }
            File file1 = new File(PHOTO_FOLDER_CARPHOTO);
            if (!file1.exists()) {
                file1.mkdirs();
            } else {
                Log.d("carphoto", PHOTO_FOLDER_CARPHOTO);
            }
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    private void initViews() {
        mToolbar = (Toolbar) findViewById(R.id.car_photo_toolbar);
        mToolbar.setTitle("现场照片");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        choosePhoImg = (ImageView) findViewById(R.id.choose_pho);
        choosePhoImg.setOnClickListener(this);
        inputFolderName = (TextView) findViewById(R.id.input_folder_name);
        carPhoRecycler = (RecyclerView) findViewById(R.id.car_pho_recyclerview);
        uploadCarPho = (Button) findViewById(R.id.upload_photo_button);
        uploadCarPho.setOnClickListener(this);
        carPhoNextBtn = (Button) findViewById(R.id.car_photo_next_btn);
        carPhoNextBtn.setOnClickListener(this);
        photoAdapter = new PhotoAdapter(this, selectedPhotos);
        carPhoRecycler.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        carPhoRecycler.setAdapter(photoAdapter);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("上传图片中");
        progressDialog.setMessage("请稍等");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choose_pho:
                PhotoPickerIntent intent = new PhotoPickerIntent(CarPhotoActivity.this);
                intent.setPhotoCount(20);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.upload_photo_button:
                progressDialog.show();
                time = System.currentTimeMillis();
                for (int i = 0; i < selectedPhotos.size(); i++) {
                    String path = selectedPhotos.get(i);
                    Bitmap bitmap = getBitmapFromFile(path);
                    bitmap = resizeBitmap(bitmap, 600);
                    saveBitmap(bitmap, time + PHOTO_NAME + i);
                }
                List<File> fileList = new ArrayList<>();
                for (int i = 0; i < selectedPhotos.size(); i++) {
                    File file = new File(PHOTO_FOLDER_CARPHOTO, time + PHOTO_NAME + i + ".jpg");
                    fileList.add(file);
                }
                File[] files = (File[]) fileList.toArray(new File[fileList.size()]);
                Log.d("carpho", files.toString());
                List<String> stringList = new ArrayList<>();
                for (int i = 0; i < selectedPhotos.size(); i++) {
                    stringList.add(i + "");
                }
                String[] strings = (String[]) stringList.toArray(new String[stringList.size()]);
                Log.d("carpho", strings.toString());
                if (selectedPhotos.size() == 0) {
                    showTextToast("没有照片可以上传");
                } else {
                    Log.d("carpho", Config.UPLOADIMGS + orderId + "&driverid=" + driverId + "&type=" + type);
                    try {
                        OkHttpClientManager.postAsyn(Config.UPLOADIMGS + orderId + "&driverid=" + driverId + "&type=" + type, new OkHttpClientManager.StringCallback() {
                            @Override
                            public void onFailure(Request request, IOException e) {
                                Log.d("jpg", "error");
                                progressDialog.dismiss();
                                showTextToast("上传失败");
                            }

                            @Override
                            public void onResponse(String response) {
                                Log.d("jpg", response);
                                progressDialog.dismiss();
                                showTextToast("上传成功");
                            }
                        }, files, strings, new OkHttpClientManager.Param("test", "test"));
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.d("jpg", "e");
                        showTextToast("上传失败");
                        progressDialog.dismiss();
                    }
                }
                break;
            case R.id.car_photo_next_btn:
                if (FROMWHERE.equals("personpho")) {
                    Intent intent1 = new Intent(CarPhotoActivity.this, CompanyActivity.class);
                    startActivity(intent1);
                    finish();
                } else if (FROMWHERE.equals("returncar")) {
                    Intent intent2 = new Intent(CarPhotoActivity.this, StartDaohangActivity.class);
                    intent2.putExtra("from", "returncar");
                    startActivity(intent2);
                    finish();
                } else if (FROMWHERE.equals("caseinfo")) {
                    finish();
                } else if (FROMWHERE.equals("casereturn")) {
                    finish();
                }
                break;
            default:
                break;
        }
    }

    public void previewPhoto(Intent intent) {
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        List<String> photos = null;
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();
            if (photos != null) {
                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 保存图片到具体位置
     *
     * @param bitmap
     */
    public void saveBitmap(Bitmap bitmap, String saveName) {
        File f = new File(PHOTO_FOLDER_CARPHOTO, saveName + ".jpg");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 固定宽度压缩图片
     *
     * @param bitmap
     * @param newWidth
     * @return
     */
    public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float temp = ((float) height) / ((float) width);
        int newHeight = (int) ((newWidth) * temp);
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        //  bitmap.recycle();
        return resizedBitmap;
    }

    /**
     * 从存储路径获取bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmapFromFile(String filePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        return bitmap;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_car_photo, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (FROMWHERE.equals("personpho")) {
            showBackDialog();
        } else if (FROMWHERE.equals("returncar")) {
            showBackDialog();
        } else if (FROMWHERE.equals("caseinfo")) {
            finish();
        } else if (FROMWHERE.equals("casereturn")) {
            finish();
        }
    }

    private void showBackDialog() {
        new MaterialDialog.Builder(this)
                .title("退出任务")
                .content("点击确定将退出您正在执行的任务。")
                .positiveText("确定")
                .negativeText("取消")
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        finish();
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }
                })
                .show();
    }
}
